package com.logos.common.widget;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

/**
 * 功能描述: Grid 间距设置
 * <p>
 * 作者: July
 * 日期: 2018/12/15 3:19 PM
 */
public class GridMainItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private int spacingTop;
    private int spacingBottom;
    private boolean includeEdge;

    public GridMainItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.spacingTop = spacing;
        this.spacingBottom = spacing;
        this.includeEdge = includeEdge;
    }

    public void setSpacingTop(int spacingTop) {
        this.spacingTop = spacingTop;
    }

    public void setSpacingBottom(int spacingBottom) {
        this.spacingBottom = spacingBottom;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int column = position % spanCount;

        if (spanCount == 1 && view.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams
                &&((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getLayoutDirection()== StaggeredGridLayoutManager.HORIZONTAL){
            outRect.left = 0;
            outRect.right =  spacing;
        }else {
            if (spanCount == 2 && view.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {
                StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
                if (params.getSpanIndex() % spanCount == 0) {
                    outRect.left = spacing;
                    outRect.right = spacing / 2;
                } else {
                    outRect.left = spacing / 2;
                    outRect.right = spacing;
                }
            } else if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount;
                outRect.right = (column + 1) * spacing / spanCount;
            } else {
                outRect.left = column * spacing / spanCount;
                outRect.right = spacing - (column + 1) * spacing / spanCount;
            }

            // 顶部间距
            if (position < spanCount && spacingTop > 0) {
                outRect.top = spacingTop;
            }

            // 底部间距
            if (spacingBottom > 0) {
                outRect.bottom = spacingBottom;
            }
        }

    }
}
